import { message } from "antd";
import apis from "./pushSceneApi";

const initState = {
  pushSceneList: [],
  totalCount: 0,
  totalPage: 0,
  showModal: false,
  currentData: {},
  sceneTypeList: [],
  filter: {
    sceneName: undefined,
    comment: undefined,
    pageIndex: 1,
    pageSize: 12
  }
};

export default {
  namespace: "pushScene",
  state: { ...initState },
  effects: {
    *pushSceneQuery({ payload = {} }, { call, put, select }) {
      const filter = yield select(state => state.pushScene.filter);
      const newFilter = { ...filter, ...payload };
      yield put({ type: "update/filter", payload: newFilter });
      const { data: pushSceneList, totalCount, totalPage } = yield call(
        apis.pushSceneQuery,
        newFilter
      );
      yield put({
        type: "save/pushSceneList",
        payload: { pushSceneList, totalCount, totalPage }
      });
    },
    // 推送场景新增/修改
    *pushSceneAdd({ payload = {} }, { call, put }) {
      const { errCode, errMsg } = yield call(apis.pushSceneAdd, payload);
      if (errCode === 0) {
        yield put({ type: "pushSceneQuery", payload: { pageIndex: 1 } });
        message.success(errMsg);
        yield put({
          type: "setState",
          payload: { showModal: false, currentData: {} }
        });
      }
    },
    // 推送场景删除
    *pushSceneDel({ payload }, { call, put }) {
      const { errCode, errMsg } = yield call(apis.pushSceneDel, payload);
      if (errCode === 0) {
        yield put({ type: "pushSceneQuery", payload: { pageIndex: 1 } });
        message.success(errMsg);
      }
    },
    *getSceneType(empty, { call, put }) {
      const { errCode, data = [] } = yield call(apis.getSceneType);
      if (errCode === 0) {
        yield put({ type: "save/sceneTypeList", payload: data });
      }
    }
  },
  reducers: {
    "save/pushSceneList": (
      state,
      { payload: { pushSceneList = [], totalCount = 0, totalPage = 0 } }
    ) => ({
      ...state,
      pushSceneList,
      totalCount,
      totalPage
    }),
    "save/sceneTypeList": (state, { payload: sceneTypeList = [] }) => ({
      ...state,
      sceneTypeList
    }),
    "update/filter": (state, { payload = {} }) => ({
      ...state,
      filter: payload
    }),
    setState: (state, { payload = {} }) => ({
      ...state,
      ...payload
    }),
    clearState: () => ({ ...initState })
  }
};
